from sqlalchemy.orm import Session

from app.models import DayAheadPlan, DayAheadPlanResource
from app.schemas.platform import GetDayaheadPlanRequest
from common.time import get_datetime_now


def save_dayahead_plan(db: Session, payload: GetDayaheadPlanRequest):
    """
    保存次日需求响应曲线
    """
    dayahead_plan = DayAheadPlan(
        plan_code=payload.planCode,
        plan_time=payload.planTime,
        create_time=get_datetime_now(),
        plan_name=payload.planName,
        invitation_id=payload.invitationId,
    )
    db.add(dayahead_plan)
    for resource in payload.responsePlan:
        for key, value in resource["declare"].items():
            dayahead_plan_resources = DayAheadPlanResource(
                invitation_id=payload.invitationId,
                resource_id=resource["resourceId"],
                key=key,
                value=value,
            )
            db.add(dayahead_plan_resources)
    db.commit()
